﻿//yyyy -- 通讯模块
type HttpMethod = "GET" | "POST" | "PUT" | "DELETE";

export class NetworkManager {
  private static _instance: NetworkManager;

  private constructor() {}

  public static getInstance(): NetworkManager {
    if (this._instance == null) {
      this._instance = new NetworkManager();
    }
    return this._instance;
  }

  //服务器地址
  private readonly serverURL: string = "https://bh.xtgame.top/gate";
  //渠道码
  private readonly channelCode: string = "DGRJ";

  /**
   * 通用请求方法
   * @param method HTTP方法
   * @param endpoint 接口路径
   * @param data 请求体数据（仅用于POST/PUT）
   * @param params URL参数对象（用于GET/DELETE）
   * @param headers 自定义请求头
   */
  private request<T>(
    method: HttpMethod,
    endpoint: string,
    data?: any,
    params?: Record<string, any>,
    headers: Record<string, string> = {
      "Content-Type": "application/json;charset=utf-8",
    }
  ): Promise<T> {
    return new Promise((resolve, reject) => {
      let fullUrl = this.serverURL + endpoint;

      // 拼接 URL 参数
      if (params) {
        const queryString = Object.entries(params)
          .filter(([_, value]) => value !== undefined && value !== null)
          .map(
            ([key, value]) =>
              `${encodeURIComponent(key)}=${encodeURIComponent(value)}`
          )
          .join("&");
        if (queryString) {
          fullUrl += (fullUrl.includes("?") ? "&" : "?") + queryString;
        }
      }

      const xhr = new XMLHttpRequest();
      xhr.open(method, fullUrl, true);

      // 设置请求头
      for (const [key, value] of Object.entries(headers)) {
        xhr.setRequestHeader(key, value);
      }

      xhr.onreadystatechange = () => {
        if (xhr.readyState === 4) {
          if (xhr.status >= 200 && xhr.status < 300) {
            try {
              const response = JSON.parse(xhr.responseText);
              resolve(response);
            } catch (e) {
              console.error("JSON解析失败:", xhr.responseText);
              reject("JSON解析失败");
            }
          } else {
            reject(`网络错误(${xhr.status}): ${xhr.statusText}`);
          }
        }
      };

      xhr.onerror = (err) => {
        reject(`请求失败: ${err}`);
      };

      // 发送请求体
      if (method === "POST" || method === "PUT") {
        // //console.log("发送数据C----->S:");
        // console.table(data);
        xhr.send(JSON.stringify(data));
      } else {
        xhr.send();
      }
    });
  }

  //注册
  public register(registerInfo: {
    account: string;
    password: string;
  }): Promise<any> {
    return this.request("POST", "/user/register", {
      uid: registerInfo.account,
      pwd: registerInfo.password,
      code: this.channelCode,
    });
  }

  //登录
  public login(loginInfo: { account: string; password: string }): Promise<any> {
    return this.request("POST", "/user/login", {
      uid: loginInfo.account,
      pwd: loginInfo.password,
      code: this.channelCode,
    });
  }

  //获取服务器时间
  public getServerTime(): Promise<any> {
    return this.request("GET", "/user/time");
  }
}
